package com.zsc.wxm.ysh.anjo.fitler;

import cn.hutool.core.collection.CollUtil;
import com.zsc.wxm.ysh.anjo.service.base.utils.SpringContext;
import com.zsc.wxm.ysh.anjo.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 描述：
 *
 * @author playmaker
 * @since 2021/2/6 16:09
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private RedisTemplate<String, String> redisTemplate = SpringContext.getBean(RedisTemplate.class);


    public TokenAuthFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        //判断如果有权限信息，放到权限上下文
        if (authenticationToken != null) {
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(token)) {
            String phone = JwtUtil.getUserPhoneByToken(token);
            if (StringUtils.isNotBlank(phone)) {
                List<String> permissionList = Collections.singletonList(redisTemplate.opsForValue().get(phone));
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                if (CollUtil.isNotEmpty(permissionList)) {
                    for (String value : permissionList) {
                        if (StringUtils.isNotBlank(value)) {
                            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(value);
                            authorities.add(authority);
                        }
                    }
                }
                return new UsernamePasswordAuthenticationToken(phone, token, authorities);
            }
        }
        return null;
    }
}
